<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件对象</title>
    <style>
        *{
            user-select: none;
            padding:0;
            margin:0;
        }
        #ad{
            width:100px;
            height: 100px;
            background:rgb(18, 7, 82);
            position:absolute;
            left: 0;
            top:0;
            /* transition: all 0.5s; */
        }
        html,body,#app{
            width: 100%;
            height: 100%;
            overflow: hidden;
            position:relative;
            background: url(zhibo.png);
            background-size: cover;
        }
    </style>
</head>
<body>
    <div id="app">
        <div id="ad"></div>
    </div>

    <script>
        let ad = document.querySelector('#ad');
        let app = document.querySelector('#app');
        //阻止默认行为
        app.addEventListener('touchstart', function(e){
            e.preventDefault();
        });

        //触摸开始
        ad.addEventListener('touchstart', function(e) {
            //移除过渡
            this.style.transition = 'none';
            this.x = e.changedTouches[0].clientX;
            this.left = this.offsetLeft;

            this.y = e.changedTouches[0].clientY;
            this.top = this.offsetTop;
        });
        //触摸移动
        ad.addEventListener('touchmove', function(e) {
            //获取手指触摸开始的位置
            let _x = e.changedTouches[0].clientX;
            let _y = e.changedTouches[0].clientY;
            //计算新的 left 的值
            let newLeft = _x - (this.x - this.left);
            let newTop = _y - (this.y - this.top);
            //判断 newLeft 的值
            if(newLeft <= 0) newLeft = 0;
            //判断右侧
            let maxWidth = app.offsetWidth - ad.offsetWidth
            if(newLeft >= maxWidth) newLeft = maxWidth;
            //设置
            this.style.left = newLeft + 'px';
            this.style.top = newTop + 'px';
        });
        
        //触摸结束
        ad.addEventListener('touchend', function(e) {
            //增加过渡
            this.style.transition = 'all 0.5s';
            //判断是偏左还是偏右
            //计算中间值
            let middle = (app.offsetWidth - ad.offsetWidth) / 2;
            //判断
            let left = ad.offsetLeft;
            //偏左
            if(left < middle){
                //
                this.style.left = '0px';
            }else{
                //获取最大的 left 的值
                let maxWidth = app.offsetWidth - ad.offsetWidth
                this.style.left = maxWidth + 'px';
            }
        });


    </script>
</body>
</html>